package com.hznu.coursemanagerbackend.modules.sys.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hznu.coursemanagerbackend.common.utils.IPUtils;
import com.hznu.coursemanagerbackend.common.utils.PageUtils;
import com.hznu.coursemanagerbackend.modules.sys.bean.ExamDetail;
import com.hznu.coursemanagerbackend.modules.sys.entity.*;
import com.hznu.coursemanagerbackend.modules.sys.service.*;
import com.hznu.coursemanagerbackend.myBeans.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author DragonDoor
 * @since 2018-11-12
 */
@EnableAutoConfiguration //自动载入应用程序所需的所有Bean
@RestController //@Controller与@ResponseBody的合并
@RequestMapping("/attendexam")
@Api(description = "参加考试记录表",value = "attendexam")
public class AttendexamController {

    @Autowired
    AttendexamService attendExamService;

    @Autowired
    UserService userService;

    @Autowired
    StudentInfoService studentInfoService;

    @Autowired
    CourseStudentService courseStudentService;

    @Autowired
    ExamCourseteachService examCourseteachService;

    @Autowired
    ExamService examService;

    /**
     * @author: Wqd
     * @Date: 2018/12/20
     * @Description:
     */
    @ApiOperation("根据考试id查找所有学生")
    @PostMapping("/findstudentsbyexamid")
    public R findstudentsbyexamid(@RequestParam Map<String,Object> params) {
        PageUtils page = attendExamService.queryPageByExamId(params);
        return R.ok().put("page", page);
    }

    /**
     * @author: DragonDoor
     * @Date: 2018/12/27 18:16
     * @Description: 
     */
    @ApiOperation("根据学生id查找所有考试")
    @GetMapping("/findExamsByStudentid/{studentid}")
    public R findExamsByStudentid(@PathVariable Integer studentid)
    {
        List<ExamDetail> attendexams = attendExamService.findExamsByStudentid(studentid);
        return R.ok().put("attendexams",attendexams);
    }

    @ApiOperation("单个添加学生")
    @PostMapping("/add")
    public R add(@RequestBody Attendexam attendexam){
        try{
            Attendexam attendexam1=new Attendexam();
            attendexam1.setExamid(attendexam.getExamid());
            User user = userService.selectOne(new EntityWrapper<User>().eq("workid",attendexam.getWorkid()));
            StudentInfo studentInfo1 = studentInfoService.selectOne(new EntityWrapper<StudentInfo>().eq("userid",user.getId()));
            attendexam1.setStudentid(studentInfo1.getId());
            if(attendExamService.selectOne(
                    new EntityWrapper<Attendexam>().eq("studentid",attendexam1.getStudentid()).and().
                            eq("examid",attendexam.getExamid())
            )==null){
                attendExamService.insert(attendexam1);
            }else{
                return R.error("该学生已参加该场考试");
            }
            return R.ok();
        }catch (Exception e){
            e.printStackTrace();
            return R.error();
        }
    }

    @ApiOperation("批量删除学生")
    @GetMapping("/removeBatch/{idList}")
    public R removeBatch(@PathVariable Integer[] idList){
        attendExamService.deleteBatchIds(Arrays.asList(idList));
        return R.ok();
    }

    @ApiOperation("添加其他授课班学生")
    @PostMapping("/addOthers")
    public R addOthers(@RequestBody Attendexam attendexam){
        for(Integer courseTeachid : attendexam.getCourseteachid()){
            Attendexam attendexam1 = new Attendexam();
            ExamCourseteach examCourseteach = new ExamCourseteach();
            examCourseteach.setExamid(attendexam.getExamid());
            examCourseteach.setCourseteachid(courseTeachid);
            examCourseteachService.insert(examCourseteach);
            List<CourseStudent> courseStudents = courseStudentService.selectList(new EntityWrapper<CourseStudent>().eq("courseteachid",courseTeachid));
            for(CourseStudent courseStudent : courseStudents){
                if(attendExamService.selectOne(new EntityWrapper<Attendexam>().eq("studentid",courseStudent.getStudentid()).eq("examid",attendexam.getExamid()))==null){
                    attendexam1.setStudentid(courseStudent.getStudentid());
                    attendexam1.setExamid(attendexam.getExamid());
                    if(attendExamService.insert(attendexam1)){
                        return R.ok("添加成功");
                    }else{
                        return R.error("已存在该学生");
                    }
                }
            }
        }
        return R.ok();
    }

    /**
     * @author: Wqd
     * @Date: 2019/1/18
     * @Description:
     */
    @ApiOperation("开始考试")
    @PostMapping("/beginExam/{attendExamid}")
    public R beginExam(HttpServletRequest request,@PathVariable Integer attendExamid)
    {
        try
        {
            Attendexam attendexam = attendExamService.selectById(attendExamid);
            Exam exam = examService.selectById(attendexam.getExamid());
            if(attendexam.getStarttime()==null){


                Timestamp curtime = new Timestamp(System.currentTimeMillis());
                attendexam.setStarttime(curtime);
                attendexam.setLoginip(IPUtils.getIpAddr(request));
                attendexam.setRemain(exam.getDuration()*60);
                attendExamService.updateById(attendexam);
                return R.ok().put("data",exam.getDuration()*60);
            }else if(attendexam.getStarttime()!=null&&attendexam.getEndtime()==null){
                Long time1 = exam.getDuration()*60-(System.currentTimeMillis()-attendexam.getStarttime().getTime())/1000;
                Long time2 = exam.getFinishtime().getTime()- System.currentTimeMillis()/1000;
                if(time1<0){
                    return R.ok().put("data",0);
                }else{
                    return R.ok().put("data",Math.min(time1,time2));
                }
            }else{
                return R.error("考生已交卷");
            }
        }catch (Exception e)
        {
            e.printStackTrace();
            return R.error();
        }
    }

    @ApiOperation("返回对应教学班的考试学生")
    @GetMapping("/findStudentByExamidAndCourseteachid/{examid}/{courseteachid}")
    public R findStudentByExamidAndCourseteachid(@PathVariable Integer examid,@PathVariable Integer courseteachid)
    {
        try
        {
            return R.ok().put("list",attendExamService.findStudentByExamidAndCourseteachid(examid,courseteachid));
        }catch (Exception e)
        {
            e.printStackTrace();
            return R.error();
        }
    }

    @ApiOperation("学生考试剩余时间减少（参加考试id）（减少秒数）")
    @GetMapping("/remainReduce/{attendExamid}/{sec}")
    public R remainReduce(@PathVariable Integer attendExamid ,@PathVariable Integer sec)
    {
        try
        {
            Attendexam attendexam = attendExamService.remainReduce(attendExamid,sec);
            return R.ok().put("data",attendexam);
        }catch (Exception e)
        {
            e.printStackTrace();
            return R.error();
        }

    }
}

